<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="oper === 'view'" label-width="9rem">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="审批模版编码" prop="approveCode">
          <el-input v-model="obj.approveCode" placeholder="自动生成" disabled style="width: 300px;" />
        </el-form-item>
        <el-form-item label="审批模版名称" prop="approveName">
          <el-input v-model="obj.approveName" placeholder="请输入审批模版名称，最多输入200个字符" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="审批模版类型" prop="approveType">
          <el-radio-group v-model="obj.approveType" @change="refreshForm('approveType')">
            <el-radio-button v-for="(item,index) in getEnumList('ApproveType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="系统模块" prop="module" v-if="['2','3','4'].includes(obj.approveType)">
          <el-radio-group v-model="obj.module" @change="refreshForm('module')">
            <el-radio-button v-for="(item,index) in approveModuleArr" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="业务模块" prop="business" v-if="['3','4'].includes(obj.approveType)">
          <el-radio-group v-model="obj.business" @change="refreshForm('business')">
            <el-radio-button v-for="(item,index) in approveBusinessArr" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级权重" prop="weight">
          <el-input-number v-model="obj.weight" placeholder="数字越大优先级越高" :min="0" :precision="0" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-switch v-model="obj.state" active-value="1" active-text="启用" inactive-value="0" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="负责部门" prop="organizationId">
          <Organization v-model="obj.organizationId" keyName="id" keyShow="organizationName" placeholder="负责部门" title="组织架构查询" />
        </el-form-item>
        <el-form-item label="负责用户" prop="userId">
          <User v-model="obj.userId" keyName="id" keyShow="name" placeholder="负责用户" title="用户查询" />
        </el-form-item>
        <el-tabs v-model="activeTabName" class="demo-tabs">
          <el-tab-pane label="审批模版节点配置" name="1"></el-tab-pane>
          <el-tab-pane label="审批模版条件配置" name="2" v-if="obj.approveType === '4'"></el-tab-pane>
        </el-tabs>
        <div class="tabs-list" v-show="activeTabName === '1'">
          <el-form-item>
            <el-button type="success" @click="addApproveNode">新增审批节点</el-button><span style="margin-left: 10px;" v-if="approveNodeList.length >= maxNodes">最多可以添加{{maxNodes}}个节点</span>
          </el-form-item>
          <el-form-item label="审批流">
            <el-timeline>
              <el-timeline-item placement="top" v-for="(node, index) in approveNodeList" :key="index" :timestamp="`审批节点${node.approveNodeNo}`" center>
                <el-card class="update-log" shadow="hover">
                  <el-form-item label="审批节点名称">
                    <el-input v-model="node.approveNodeName" placeholder="请输入节点名称" style="width: 300px;" />
                  </el-form-item>
                  <el-form-item label="是否会签节点" style="margin: 10px 0;">
                    <el-radio-group v-model="node.isCountersign" @change="node.approveNodeType = '2'">
                      <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="审批节点类型" style="margin: 10px 0;">
                    <el-radio-group v-model="node.approveNodeType"
                                    :disabled="node.isCountersign === '1'"
                                    @change="node.approveNodeOrgId = null;node.approveNodeUserId = null;node.approveNodeRoleId = null;">
                      <el-radio-button v-for="(item,index) in getEnumList('ApproveNodeType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="审批节点组织架构" v-if="node.approveNodeType === '1'">
                    <Organization v-model="node.approveNodeOrgId" keyName="id" keyShow="organizationName" isMultiple placeholder="部门" title="部门查询" />
                  </el-form-item>
                  <el-form-item label="审批节点用户" v-if="node.approveNodeType === '2'">
                    <User v-model="node.approveNodeUserId" keyName="id" keyShow="name" isMultiple placeholder="用户" title="用户查询" />
                  </el-form-item>
                  <el-form-item label="审批节点角色" v-if="node.approveNodeType === '3'">
                    <Role v-model="node.approveNodeRoleId" keyName="id" keyShow="roleName" isMultiple placeholder="角色" title="角色查询" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="danger" @click="delApproveNode(node.approveNodeNo)">删除该节点</el-button>
                  </el-form-item>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-form-item>
        </div>
        <div class="tabs-list" v-show="activeTabName === '2'">
            <div v-for="(item, index) in approveConditionList" :key="index">
              <el-form-item :label="item.approveConditionLabel" v-if="item.approveConditionOper === 'BETWEEN'">
                <el-input-number v-model="item.approveConditionValueArr[0]"></el-input-number>
                &nbsp;-&nbsp;
                <el-input-number v-model="item.approveConditionValueArr[1]"></el-input-number>
              </el-form-item>
              <el-form-item :label="item.approveConditionLabel" v-if="item.approveConditionOper === 'IN'">
                <el-checkbox-group v-model="item.approveConditionValueArr">
                  <el-checkbox v-for="m in item.approveConditionValueOptions" :key="m.key" :label="m.key">
                    {{ m.value }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </div>
      </el-form>
      <div style="text-align:center;">
        <el-button v-show="oper !== 'view'" type="primary" @click="doConfirm('obj')">
          <svg-icon icon-class="save" />
          保存
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import baseConfig from "@/mixins/baseConfig";
import {doGet, doPost} from "@/config/http";
import {alertErrorMsg, customValidator, getListPageSize, isNullOrUndefined, notifySuccess, initListUpdate} from "@/config/common";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'
import User from "@/views/components/base/selectUserOrg.vue";
import Role from "@/views/components/base/selectRole.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import {getUserId} from "@/config/cookie";

const emptyApproveNode = {
  approveNodeName: '审批节点1',
  approveNodeType: '',
  approveNodeOrgId: null,
  approveNodeRoleId: null,
  approveNodeUserId: null,
  approveNodeNo: 1,
  isCountersign: '0', // 是否会签节点
}

const emptyObj = {
  approveCode: null, // 审批模版编码
  approveName: null, // 审批模版名称
  approveType: null, //
  state: '1', // 状态
  organizationId: null,//useUserStore().organization.id, // 负责部门
  userId: null,//getUserId(), // 负责用户
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'approveTemplateEdit_nocache',
  mixins: [baseConfig],
  components: {
    Organization,
    User,
    Role,
  },
  data() {
    return {
      svc: 'icims-api',
      routes: [],
      rules: {
        approveCode: [{ required: false, validator: customValidator, min: 0, max: 100, label: '审批模版编码', trigger: ['blur', 'change'] }],
        approveName: [{ required: true, validator: customValidator, min: 1, max: 200, label: '审批模版名称', trigger: ['blur', 'change'] }],
        approveType: [{ required: true, validator: customValidator, min: 1, max: 200, label: '审批模版类型', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        organizationId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '负责部门', trigger: ['blur', 'change'] }],
        userId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '负责用户', trigger: ['blur', 'change'] }],
        module: [{ required: false, validator: customValidator, min: 0, max: 20, label: '系统模块', trigger: ['blur', 'change'] }],
        business: [{ required: false, validator: customValidator, min: 0, max: 20, label: '业务模块', trigger: ['blur', 'change'] }],
        weight: [{ required: false, validator: customValidator, min: 0, max: 9, label: '优先级权重', trigger: ['blur', 'change'] }],
      },
      id: null,
      obj: Object.assign({}, emptyObj),
      approveNodeNum: 1,
      oper: null,
      approveConfigList: initListStore().approveConfigList,// 审批配置
      approveModuleArr: [],
      approveBusinessArr: [],
      userList: initListStore().userList,
      organizationList: initListStore().organizationList,
      roleList: initListStore().roleList,
      approveNodeList: [ Object.assign({}, emptyApproveNode) ],
      approveConditionList: [],
      activeTabName: '1',
      maxNodes: 10,
    }
  },
  computed: {
  },
  created() {
    this.initObj()
    // this.initList()
  },
  methods: {
    useUserStore,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/role/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/customApprove/approveConfig', {}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4])
    //   this.userList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.roleList = resArray[2]['records']
    //   this.approveConfigList = resArray[3]
    // },
    async initObj() {
      this.oper = this.$route.query.oper
      this.id = null
      if (this.oper !== 'add' && this.$route.query.id) {
        this.id = this.$route.query.id
        this.obj = await doGet(this.svc, '/approve/' + this.id, {}, true)
        this.approveNodeList = await doGet(this.svc, '/approve-node/listByField', {field:'approveId', values:this.id}, false)
        this.approveConditionList = await doGet(this.svc, '/approve-condition/listByField', {field:'approveId', values:this.id}, false)
        console.debug('approveConditionList',this.approveConditionList)
      }
      this.refreshForm('approveType')
    },
    refreshForm(point) {
      switch (point) {
        case 'approveType': {
          this.activeTabName = '1';
          // this.obj.module = null;
          // this.obj.business = null;
          this.approveModuleArr = this.approveConfigList;
          this.approveBusinessArr = this.approveConfigList.filter(item => item.key === this.obj.module)[0]?.children;
          switch (this.obj.approveType) {
            case '1':
              this.rules.module[0].required = false
              this.rules.business[0].required = false
              this.rules.weight[0].required = false
              break;
            case '2':
              this.rules.module[0].required = true
              this.rules.business[0].required = false
              this.rules.weight[0].required = false
              break;
            case '3':
              this.rules.module[0].required = true
              this.rules.business[0].required = true
              this.rules.weight[0].required = false
              break;
            case '4':
              this.rules.module[0].required = true
              this.rules.business[0].required = true
              this.rules.weight[0].required = true
              break;
          }
          break;
        }
        case 'module': {
          this.activeTabName = '1';
          // this.obj.business = null;
          this.approveModuleArr = this.approveConfigList;
          this.approveBusinessArr = this.approveConfigList.filter(item => item.key === this.obj.module)[0]?.children;
          break;
        }
        case 'business': {
          this.approveModuleArr = this.approveConfigList;
          this.approveBusinessArr = this.approveConfigList.filter(item => item.key === this.obj.module)[0]?.children;
          break;
        }
      }
      let biz = this.approveBusinessArr?.filter(item => item.key === this.obj.business)[0]
      console.debug('this.approveConditionList',this.approveConditionList)
      // this.approveConditionList = []
      const valueOptions = []
      biz?.children.map(item => {
        let m = {
          approveConditionBusiness: biz.key,
          approveConditionField: item.key,
          approveConditionLabel: item.value,
          approveConditionOper: item.valueType,
          approveConditionValues: null,
          approveConditionValueArr: this.approveConditionList.filter(a => a.approveConditionField === item.key)[0]?.approveConditionValues.split(','),
          approveConditionValueOptions: item.children,
        }
        if (isNullOrUndefined(m.approveConditionValueArr)) {
          m.approveConditionValueArr = [null,null]
        }
        console.debug('m.approveConditionValueArr',m.approveConditionValueArr)
        valueOptions.push(m)
      })
      this.approveConditionList = valueOptions
    },
    addApproveNode() {
      if (this.approveNodeList.length >= this.maxNodes) {
        return
      }
      let o = Object.assign({}, emptyApproveNode)
      let nodeIdx = this.approveNodeList.length + 1
      o.approveNodeNo = nodeIdx
      o.approveNodeName = '审批节点' + nodeIdx
      this.approveNodeList.push(o)
    },
    delApproveNode(nodeIdx) {
      let idx = this.approveNodeList.findIndex(item => item.approveNodeNo === nodeIdx)
      this.approveNodeList.splice(idx, 1)
      for (let i in this.approveNodeList) {
        this.approveNodeList[i].approveNodeNo = (parseInt(i) + 1)
        this.approveNodeList[i].approveNodeName = '审批节点' + (parseInt(i) + 1)
      }
    },
    checkForm() {
      let users = []
      let orgs = []
      if (this.approveNodeList.length === 0) {
        alertErrorMsg("请添加审批节点")
        return false
      }
      for (let i in this.approveNodeList) {
        if (!this.approveNodeList[i].approveNodeType) {
          alertErrorMsg('请选择审批节点类型')
          return false
        }
        if (this.approveNodeList[i].approveNodeType === '1') {
          if (!this.approveNodeList[i].approveNodeOrgId) {
            alertErrorMsg('请选择组织架构')
            return false
          }
          if (orgs.indexOf(this.approveNodeList[i].approveNodeOrgId) > -1) {
            alertErrorMsg('组织架构重复')
            return false
          }
          orgs.push(this.approveNodeList[i].approveNodeOrgId)
        }
        if (this.approveNodeList[i].approveNodeType === '2') {
          if (!this.approveNodeList[i].approveNodeUserId) {
            alertErrorMsg('请选择用户')
            return false
          }
          if (users.indexOf(this.approveNodeList[i].approveNodeUserId) > -1) {
            alertErrorMsg('用户重复')
            return false
          }
          users.push(this.approveNodeList[i].approveNodeUserId)
        }
        if (this.approveNodeList[i].approveNodeType === '3') {
          if (!this.approveNodeList[i].approveNodeRoleId) {
            alertErrorMsg('请选择用户')
            return false
          }
          if (users.indexOf(this.approveNodeList[i].approveNodeRoleId) > -1) {
            alertErrorMsg('用户重复')
            return false
          }
          users.push(this.approveNodeList[i].approveNodeRoleId)
        }
      }
      return true
    },
    async doConfirm(formName) {
      this.approveConditionList.map(item => item.approveConditionValues = item.approveConditionValueArr?.join(","))
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (!this.checkForm())
        return
      this.obj.nodes = this.approveNodeList
      this.obj.conditions = this.approveConditionList
      doPost(this.svc, '/customApprove/saveApprove', this.obj).then(() => {
        notifySuccess('操作成功')
        initListUpdate('approveList', '/approve/page')
        this.goTargetByName('approveTemplate', {}, true)
        this.dialogVisible = false
      })
    },
  },
}
</script>
